package org.gp.core.interceptors;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.gp.core.annotation.AuthOperate;
import org.gp.core.entity.TokenModel;
import org.gp.core.service.TokenManager;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by luoliang on 2017/1/30.
 */
@Slf4j
@Component
public class WxAuthInterceptor implements HandlerInterceptor {
    @Resource
    private TokenManager tokenManager;

    private final static String HEARTBEAT = "admin";

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        log.info("请求接口：" + httpServletRequest.getRequestURL().toString());

        //如果不是映射方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //从header中取得token
        String token = httpServletRequest.getHeader("token");

        TokenModel tokenModel = new TokenModel();
        tokenModel.setId("admin");
        tokenModel.setToken(token);
        if (method.getAnnotation(AuthOperate.class) != null && !StringUtils.isEmpty(token) && !tokenManager.checkToken(tokenModel)) {
            httpServletResponse.setStatus(401);
            httpServletResponse.setHeader("msg", "权限验证未通过");
//            throw new BusinessException("权限验证未通过!");
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
